import React, { useRef, useState, useEffect, useCallback } from "react";
import { Breadcrumb, Col, Form, Input, Button, Row, message, Result, Tabs, Space, Checkbox, Select, } from 'antd';
import { UploadPhotoToServer, WangEditor5, XxDatePicker, XxSelect, XxtreeSelect, XxUploadPhotoList, } from '@/ui';
import { artApi, subjectApi } from "@/api";
import { useLocation } from "react-router-dom";
import styls from './editArticle.module.scss'
import { mobxState } from "@/data";
import { errorAlert } from "@/common/methods";
const { TextArea } = Input;



/**
 * 
 * @description 新建|编辑内容页面
 * @param {} param0 
 * @returns 
 */
const EditArticle = () => {
    // const previeRef = useRef();
    const [action, setAction] = useState("add");
    const location = useLocation();
    const [form] = Form.useForm();
    const [record, setRecord] = useState({})



    const getDetail = async (params) => {
        try {
            const { data, code, msg } = await artApi.getDetail(params);
            const { id, title, intro, subjectId, masterImage, description, status, sort,
                seoDescription,
                seoTitle,
                urlname,
                keyWords, } = data;
            setRecord(data)
            form.setFieldsValue({
                id, title, intro, subjectId,
                masterImage: masterImage, description, status, sort, seoDescription,
                seoTitle,
                urlname,
                keyWords,
            })
        } catch (error) {
            errorAlert("获取详情失败：" + error)
        }
    }


    useEffect(() => {
        const { id = null, action = "add" } = location?.state;
        if (id && action === "update") {
            getDetail(id)
        }
    }, [location])


    const BreadcrumbItems = [
        {
            title: "内容管理",
            onClick: () => { }
        },
        {
            title: "文章",
            onClick: () => { }
        },
        {
            title: action === "update" ? "编辑" : "新建",
            onClick: () => { }
        }
    ]



    /**@description 保存文章数据 */
    const saveData = async (values) => {
        const { data, code, msg } = await artApi.create({ ...values });
        if (code === 0) {
            message.success("保存成功")
            setTimeout(() => {

            }, 1000)
            mobxState.closeTab("context_type_edit_form")
        }

    }


    /**@description 专题列表 */
    const [subjectList, setSubjectList] = useState([]);

    /**@description 获取专题列表 */
    const getSubjectList = async (classId) => {
        try {
            const { data, code, msg } = await subjectApi.queryList({ pageSize: 1000, current: 1, classId: classId });
            if (data.list && data.list.length > 0) {
                setSubjectList(data.list)
            }
        } catch (error) {
            console.log("报错了", error)
        }
    }

    useEffect(() => {
        getSubjectList();
    }, [])





    // 点击提交
    const submit = () => {
        form.validateFields().then(values => {
            let paramsFormData = {
                ...record,
                ...values,
            }
            console.log("表单校验：", paramsFormData)
            saveData(paramsFormData)
        }).catch(error => {
            console.log("校验失败：", error)
        })
    }




    const BasicInfo = () => {
        return (
            <Row gutter={24}>
                <Col span={24} style={{ display: "none" }}>
                    <Form.Item name='id' label="id">
                        <Input />
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item name='title' label="标题">
                        <Input />
                    </Form.Item>
                </Col>
                <Col span={24}>

                    <Form.Item label="封面" name="masterImage">
                        <UploadPhotoToServer />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item name='subjectId' label="专题分类">
                        <XxtreeSelect treeData={subjectList} fieldNames={{
                            label: "title",
                            value: "id",
                            children: 'children'
                        }} />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item name='publishTime' label="发布时间">
                        <XxDatePicker placeholder="发布时间" format="YYYY-MM-DD HH:mm:ss" showTime pick="date" />
                    </Form.Item>
                </Col>
                <Col span={24}>
                    <Form.Item name='modules' label="模板">
                        <XxSelect />
                    </Form.Item>
                </Col>
            </Row>
        )
    }

    const ContentDetail = () => {
        return (
            <Form.Item name="description" className="content-formItem">
                <WangEditor5 />
            </Form.Item>
        )
    }



    const SEOConfig = () => {
        const optionsWithDisabled = [{
            label: "允许搜索引擎搜索快照",
            value: "takeDown"
        },
        {
            label: "允许搜索引擎收录",
            value: "snapshot"
        }
        ]
        return (
            <Col span={24} >
                <Form.Item name="seoTitle" label="SEO标题">
                    <Input />
                </Form.Item>
                <Form.Item name="seoDescription" label="meta描述">
                    <TextArea />
                </Form.Item>
                <Form.Item name="keyWords" label="关键词">
                    <Input />
                </Form.Item>
                <Form.Item name="urlname" label="URL别名">
                    <Input />
                </Form.Item>
                <Form.Item name="searchEngine" label="搜索引擎">
                    <Checkbox.Group
                        options={optionsWithDisabled}
                        defaultValue={['takeDown', 'snapshot']}
                    >
                        <Row gutter={24}>
                            {
                                optionsWithDisabled.map((item, key) => (
                                    <>
                                        <Col span={24} key={key}>
                                            <Checkbox value={item.value}>{item.label}</Checkbox>
                                        </Col>
                                        <br />
                                    </>
                                ))
                            }
                        </Row>
                    </Checkbox.Group>
                </Form.Item>

            </Col>

        )
    }

    const items = [
        {
            label: "基本信息",
            children: <BasicInfo />,
            key: "1",
        }
        ,
        {
            label: "内容详情",
            children: <ContentDetail />,
            key: "2",
        }
        ,
        {
            label: "SEO配置",
            children: <SEOConfig />,
            key: "3",
        }
    ]





    return (
        <>


            <div className={styls.editStyles}>
                <div className="header">
                    <Breadcrumb items={BreadcrumbItems} style={{ backgroundColor: 'white', }} />
                    <Button type="primary" onClick={submit}>发布</Button>
                </div>
                <div className="center">
                    <div className="edit-content">
                        <Form
                            layout="vertical"
                            form={form}
                            wrapperCol={24}
                            className="edit-form"
                        >
                            <Tabs
                                defaultActiveKey="1"
                                items={items}
                                tabBarStyle={{
                                    padding: '0 10px',
                                }}

                                className="edit-tabs" />
                        </Form>
                    </div>
                </div>

            </div>



        </>
    )


}

export default EditArticle;